package org.idea.spring.bean.source;

import org.idea.spring.bean.scope.User;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * 单例对象的注册
 *
 * @Author linhao
 * @Date created in 9:56 上午 2021/5/3
 */
public class SingletonBeanRegister {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
        annotationConfigApplicationContext.register(SingletonBeanRegister.class);
        annotationConfigApplicationContext.register(User.class);
        DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) annotationConfigApplicationContext.getBeanFactory();
        if(defaultListableBeanFactory!=null) {
            defaultListableBeanFactory.registerSingleton("singletonUser", new User(1001,"idea"));
        }
        annotationConfigApplicationContext.refresh();
        User singletonUser = (User) annotationConfigApplicationContext.getBean("singletonUser");
        User singletonUser2 = (User) annotationConfigApplicationContext.getBean("singletonUser");
        System.out.println(singletonUser == singletonUser2);

        User user = (User) defaultListableBeanFactory.getBean("user");
        User user2 = (User) defaultListableBeanFactory.getBean("user");
        System.out.println(user == user2);
    }
}
